import { Button, Form } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import React, { useEffect, useMemo } from 'react'
import { useRequest } from 'taro-hooks'
import AddressSelect from '../../components/address-select'
import DateTimePicker from '../../components/date-time-picker'
import FeeDetails from '../../components/fee-details'
import Layout from '../../components/layout'
import ProductCard from '../../components/product-card'
import { DATE_TIME_OPTIONS, QuotationCategory, THEME_COLORS } from '../../constants'
import { useNavigation } from '../../hooks'
import { IOrderProduct } from '../../inteface/order'
import { orderSubmit } from '../../services/appointment'
import { getProductListWithPrice } from '../../services/product'
import { getUserAddresses } from '../../services/user'
import { toast } from '../../utils'
import { parseTimeRangeToTimestamps } from '../../utils/formatDate'
import './index.less'

const FeeEstimation: React.FC = () => {
  const { params } = useNavigation()
  const packageId = params.packageId as string
  const snapShotId = params.snapShotId as string
  const [form] = Form.useForm()
  const selectedPackages = Form.useWatch('selectedPackages', form)
  const { redirectTo, navigateTo } = useNavigation()
  const { data: addressesData, loading } = useRequest(getUserAddresses)
  const { runAsync: addAppointmentRun } = useRequest(orderSubmit, { manual: true })

  const { data: productListData, loading: productListLoading } = useRequest(getProductListWithPrice, {
    defaultParams: [[{ calculate: { packageId: Number(packageId), snapShotId: Number(snapShotId) } }]],
  })

  const {
    data: praceData,
    loading: praceLoading,
    runAsync: getPriceRun,
  } = useRequest(getProductListWithPrice, {
    manual: true,
  })

  useEffect(() => {
    if (selectedPackages?.length > 0) {
      const selectItems = selectedPackages.map((id) =>
        productListData?.listProduct.find((item) => item.id === Number(id)),
      )
      const pramas = selectItems.map((items) => {
        return {
          productId: items?.id,
          calculate: {
            packageId: Number(items?.packageId),
            snapShotId: Number(items?.snapShotId),
          },
        }
      })
      getPriceRun(pramas)
    }
  }, [getPriceRun, productListData?.listProduct, selectedPackages])

  const initialPackages = useMemo(() => {
    return (
      productListData?.listProduct.map((item) => {
        return {
          id: item.id,
          name: item.name,
          price: item.totalPrice,
          image: item.style.image,
          colorStyle: item.colorScheme.name,
          area: item.spaceSize,
          style: item.style.name,
        }
      }) || []
    )
  }, [productListData])

  // 地址选择器数据
  const addresses = useMemo(() => {
    return (
      addressesData?.addresses.map((item) => {
        return {
          isDefault: item.isDefault,
          id: item.id,
          addressDetail: item.address,
          name: item.name,
          phone: item.phone,
          cityName: '',
          countyName: '',
          provinceName: '',
          townName: '',
        }
      }) || []
    )
  }, [addressesData?.addresses])

  // 项目费用明细数据
  const projectFeeCategories: QuotationCategory[] = useMemo(() => {
    return (
      praceData?.summary.categories.map((category) => {
        return {
          category: category.categoryName,
          items: category.subCategories.map((subCategory) => {
            return {
              name: subCategory.title,
              price: subCategory.totalPrice + '',
            }
          }),
          total: category.totalPrice,
        }
      }) || []
    )
  }, [praceData?.summary.categories])

  return (
    <Layout
      title='透明报价'
      showTabBar={false}
      fullLoading={loading || productListLoading}
      footer={
        <View className='p-16'>
          <Button
            block
            type='primary'
            onClick={() => {
              form.validateFields().then((values) => {
                if (values.length) {
                  toast.showError(values[0].message)
                } else {
                  form.submit()
                }
              })
            }}>
            确认预约 (已选{selectedPackages?.length}个改造包)
          </Button>
        </View>
      }>
      <View className='fee-estimation-wrapper'>
        <Form
          initialValues={{
            selectedAddress: addressesData?.addresses.find((item) => item.isDefault)?.id,
            selectedPackages: packageId ? [packageId] : [],
          }}
          form={form}
          onFinish={(values) => {
            const date = values.selectedTime.text + ' ' + values.selectedTime.children?.[0]?.text
            const timestamps = parseTimeRangeToTimestamps(date)

            // 2025-10-12 11:00-12:00
            const data: IOrderProduct = {
              beginAt: timestamps?.[0] || 0,
              endAt: timestamps?.[1] || 0,
              addressId: values.selectedAddress,
              products: values.selectedPackages.map((item: string) => ({
                productId: item,
              })),
            }
            addAppointmentRun(data).then((res) => {
              if (res?.result?.orderNo) {
                redirectTo({
                  url: `/pages/appointment-success/index?orderNo=${res?.result?.orderNo}`,
                })
              }
            })
          }}
          divider>
          {/* 地址选择 */}
          <View className='form-header'>
            <Text>选择地址</Text>
          </View>
          <Form.Item name='selectedAddress' noStyle rules={[{ required: true, message: '请选择地址' }]}>
            <AddressSelect options={addresses} />
          </Form.Item>

          {/* 时间选择 */}
          <View className='form-header'>
            <Text>选择时间</Text>
          </View>
          <Form.Item name='selectedTime' noStyle rules={[{ required: true, message: '请选择时间' }]}>
            <DateTimePicker options={DATE_TIME_OPTIONS} />
          </Form.Item>

          {/* 套餐选择 */}
          <View className='form-header'>
            <Text>装修项目</Text>
            <Text className='form-header-desc'>请选择您的 装修项目</Text>
          </View>
          <Form.Item name='selectedPackages' noStyle rules={[{ required: true, message: '请选择套餐' }]}>
            <ProductCard
              options={initialPackages}
              showExtra
              onExtraClick={(option) => {
                navigateTo({
                  url: `/pages/package-selection/index`,
                  params: {
                    projectId: option.id,
                    packageId: option?.packageId || '',
                    snapShotId: option?.snapShotId || '', //TODO: 哪里获取？
                  },
                })
              }}
            />
          </Form.Item>

          <View className='form-header'>
            <Text>装修项目</Text>
            <Text className='form-header-desc'>请选择您的 装修项目</Text>
          </View>
          <Form.Item>
            <FeeDetails
              loading={praceLoading}
              showTitle={false}
              showCard={false}
              categories={projectFeeCategories}
              totalAmount={productListData?.summary?.totalPrice?.toString()}
              title='项目费用明细'
              primaryColor={THEME_COLORS.primary}
              note='*此报价为估算价格，最终价格以实际测量和材料选择为准。'
            />
          </Form.Item>
        </Form>
      </View>
    </Layout>
  )
}

export default FeeEstimation
